package day_2022_9_to_12.Day;

/**
 * @author haomin
 * @date 2022/09/07 09:20
 **/
public class Day5_1_Num1592_ReorderSpaces {
    class Solution {
        public String reorderSpaces(String text) {
            int calcSum = 0, calcLetter = 0;
            for(int i = 0; i < text.length(); ++i){
                if(text.charAt(i) == ' ') calcSum++;
            }
            String[] letters = text.split(" ");
            for(int i = 0; i < letters.length; ++i){
                if(letters[i].length() != 0) calcLetter++;
            }
            if(calcLetter == 0 || calcSum == 0) return text;
            int a = 0, b = 0;
            if(calcLetter == 1)  {a = 0; b = calcSum;}
            else if(calcLetter > 1){
                a = calcSum / (calcLetter-1);
                b = calcSum % (calcLetter-1);
            }
            StringBuffer sb = new StringBuffer();
            for(int i = 0; i < letters.length; ++i){
                if(letters[i].length() != 0){
                    sb.append(letters[i]); calcLetter--;
                    int count = a;
                    if (calcLetter == 0) count = b;
                    while(count-- > 0){
                        sb.append(" ");
                    }
                }
            }
            return sb.toString();
        }
    }
}